<?php
/**
    flickr_comm v0.1.1
    Copyright 2010 Markus Dolic (crowley@gmx.net)
    
    This file is part of the flickrpost package. 
    (http://code.google.com/p/flickrpost/)
    
    flickrpost is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version. 
    flickrpost is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
    You should have received a copy of the GNU General Public License
    along with flickrpost.  If not, see <http://www.gnu.org/licenses/>. 
**/

#error_reporting(E_ALL);
require_once(dirname(__FILE__)."/inc/common.php");


$addon_name = "flickr_comm<a name='flickr_comm'></a>";
$addon_version = "0.1.1";
$addon_description = "";

$errormsg = '';

// create config table if it does not exist yet
$res = mysql_query("SELECT * FROM $TABLE_COMM_CFG LIMIT 1");
if (!$res) {
    mysql_query("CREATE TABLE IF NOT EXISTS $TABLE_COMM_CFG (
                     `imagesubst` VARCHAR(255), 
                     `permalink` BOOL
                )");
}
if (!$res or !mysql_num_rows($res) or mysql_num_rows($res) < 1) {
    // insert default config record
	mysql_query("INSERT INTO $TABLE_COMM_CFG VALUES('[image]', 1)");
}

// populate config variables from config DB
$result = mysql_query("SELECT * FROM $TABLE_COMM_CFG LIMIT 1");
while ($cfg = mysql_fetch_array($result)) {
    $imagesubst = $cfg['imagesubst'];
    $permalink = $cfg['permalink'];
}

// initialize flickr API proxy object
// TODO: refactor with almost indentical code in flickr_sync
$result = mysql_query("SELECT * FROM $TABLE_AUTH LIMIT 1") or $errormsg .= 'Could not retrieve flickr authentication data: ' . mysql_error() . '<br />';
while ($cfg = mysql_fetch_array($result)) {
    $api_key = $cfg['api_key'];
    $api_secret = $cfg['api_secret'];
    $api_perm = $cfg['api_perm'];
    $api_token = $cfg['api_token'];
}
$_SESSION['phpFlickr_auth_token'] = $api_token;
$flickr = new phpFlickr($api_key, $api_secret, true);


// process POST requests
if (isset($_POST['flickr_comm_do'])) {
    if ($_POST['flickr_comm_do'] == 'config') {
        $imagesubst = trim($_POST['imagesubst']);
        $permalink = isset($_POST['permalink']) ? 1 : 0;
        mysql_query("UPDATE " . $TABLE_COMM_CFG . " SET imagesubst='$imagesubst', permalink='{$permalink}'") or die(mysql_error());
        $_SESSION['flickr_comm_result'] = 'Configuration saved. ';
    }
}


if (isset($_GET['showimage'])) {
    $img_id = $_GET['showimage'];
    $result = mysql_query("SELECT flickr_id FROM $TABLE_SYNC_DATA WHERE fk_pp_id = $img_id") or die(mysql_error());
    while ($row = mysql_fetch_array($result)) {
        $flickr_id = $row['flickr_id'];
        $response = $flickr->photos_comments_getList($flickr_id);
        foreach ($response['comments']['comment'] as $comm) {
            save_comment($img_id, $comm);
        }
    }
}


// build HTML for addon config page
if (isset($errormsg) and $errormsg != '') {
    $addon_description .= "<div class='confirm'>Error: <br />{$errormsg}</div><br />";
}
if (isset($_SESSION['flickr_comm_result'])) {
    $addon_description .= "<em>" . $_SESSION['flickr_comm_result'] . '</em><hr />';
    unset($_SESSION['flickr_comm_result']);
}
$permalink_checked = $permalink ? "checked='checked'" : '';
$addon_description .= <<<EOT
    <p>Configuration: </p>
    <form action='{$SITE_URL}admin/index.php?view=addons#flickr_comm' method='post' accept-charset='UTF-8'>
        <input type='hidden' name='flickr_comm_do' value='config' />
        <table>
            <tr style='vertical-align:top;'>
                <td>Replace images in comments with: </td>
                <td><input type='text' size='40' name='imagesubst' value='{$imagesubst}' /></td>
            </tr>
            <tr style='vertical-align:top;'>
                <td>Add permalink to flickr comments: </td>
                <td><input type='checkbox' name='permalink' {$permalink_checked} /></td>
            </tr>
        </table>
        <input type='submit' value='Save' />
    </form>
EOT;


function save_comment($img_id, $commdata)
{
    global $pixelpost_db_prefix, $imagesubst, $permalink;
    $datetime = strftime("%Y-%m-%d %H:%M:%S", $commdata['datecreate']);
    $msg = $commdata['_content'];
    if ($imagesubst != NULL) $msg = preg_replace("#<img[^>]*>#i", $imagesubst, $msg);  #TODO: this only applies to actual <img> tags, not [url]s
    $msg = nl2br(htmlspecialchars(strip_tags($msg), ENT_QUOTES));
    if ($permalink) $msg = "<a href='{$commdata['permalink']}'>[comment on flickr]</a><br />" . $msg;
    $msg = addslashes($msg);
    $name = addslashes(nl2br(htmlspecialchars(strip_tags($commdata['authorname']), ENT_QUOTES)));
    $url = "http://www.flickr.com/photos/{$commdata['author']}";
    $publish = 'yes';
    // add comment to DB (if it's not already there):
    $query = mysql_query("SELECT * FROM {$pixelpost_db_prefix}comments " .
                         "WHERE parent_id = '$img_id' AND datetime = '$datetime' AND name = '$name'");
    if (mysql_num_rows($query) == 0) {
        $query = "INSERT INTO {$pixelpost_db_prefix}comments (id, parent_id, datetime, ip, message, name, url, publish) " .
                 "VALUES (NULL, '$img_id', '$datetime', '', '$msg', '$name', '$url', '$publish')";
        mysql_query($query) or die(mysql_error());
    }
}

?>
